package com.wind.trademark.task.controller;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.wind.trademark.base.model.BsCategory;
import com.wind.trademark.common.exception.TmException;
import com.wind.trademark.common.vo.ComboBean;
import com.wind.trademark.common.vo.PageBean;
import com.wind.trademark.common.vo.PageParam;
import com.wind.trademark.task.model.TkAttachment;
import com.wind.trademark.task.model.TkImg;
import com.wind.trademark.task.model.TkTask;
import com.wind.trademark.task.model.TkTaskLog;
import com.wind.trademark.task.model.TkTaskStatus;
import com.wind.trademark.task.service.TaskService;
import com.wind.trademark.task.vo.AttachmentFileUploadBean;
import com.wind.trademark.task.vo.ImageFileUploadBean;
import com.wind.trademark.task.vo.TaskProfile;

@Controller
public class TaskController {
	@Value("#{properties['img.repository']}")   
	private String imgRepository;
	@Value("#{properties['file.repository']}")   
	private String fileRepository;
	@Autowired
	private TaskService taskService;

	private static final Log log = LogFactory.getLog(TaskController.class);
 

	@RequestMapping
	public @ResponseBody
	PageBean queryTask(PageParam pageParam,
			@RequestParam Map<String, Object> params) {

		PageBean pageBean = taskService.queryTask(pageParam, params);
		return pageBean;
	}

	@RequestMapping
	public @ResponseBody
	TkTask saveOrUpateTask(@RequestBody TkTask task) {
		return taskService.saveOrUpateTask(task);
	}

	@RequestMapping
	public @ResponseBody
	TkTask loadTask(Long id) {
		return taskService.getTask(id);
	}

	@RequestMapping
	public void uploadImage(ImageFileUploadBean imageFileUploadBean,HttpServletResponse httpServletResponse
			)
			throws IOException {
		httpServletResponse.setContentType("text/html;charset=UTF-8");

		// Some type of file processing...
		System.err.println("-------------------------------------------");
		System.err.println("Test upload: "
				+ imageFileUploadBean.getMultipartFile().getOriginalFilename());
		System.err.println("-------------------------------------------");
		TkImg tkImg=taskService.saveTkImg(imageFileUploadBean);
		Map<String,Object> model=new HashMap<String,Object>();
		model.put("success", "true");
		model.put("data", tkImg);
		ObjectMapper  objectMapper = new  ObjectMapper();
		objectMapper.writeValue(httpServletResponse.getWriter(), tkImg);
		//httpServletResponse.getWriter().write("{\"success\":\"true\"}");

	}
	
	@RequestMapping
	public void uploadAttachment(AttachmentFileUploadBean attachmentFileUploadBean,HttpServletResponse httpServletResponse
			)
			throws IOException {
		httpServletResponse.setContentType("text/html;charset=UTF-8");

		// Some type of file processing...
		System.err.println("-------------------------------------------");
		System.err.println("Test upload: "
				+ attachmentFileUploadBean.getMultipartFile().getOriginalFilename());
		System.err.println("-------------------------------------------");
		TkAttachment tkAttachment=taskService.saveTkAttachment(attachmentFileUploadBean);
		Map<String,Object> model=new HashMap<String,Object>();
		model.put("success", "true");
		model.put("data", tkAttachment);
		ObjectMapper  objectMapper = new  ObjectMapper();
		objectMapper.writeValue(httpServletResponse.getWriter(), tkAttachment);
		//httpServletResponse.getWriter().write("{\"success\":\"true\"}");

	}
	
	

	@RequestMapping
	public @ResponseBody
	Long[] addCategoryListToTask(Long taskId,Long categoryId,Long[] ids,HttpServletRequest httpServletRequest) {
		taskService.addCategoryListToTask(taskId,categoryId,Arrays.asList(ids));
		return ids;
	}

	@RequestMapping
	public @ResponseBody
	List<BsCategory> getL3CategoriesByTaskId(@RequestParam(required=true)Long taskId) {

		List<BsCategory> list = taskService.getL3CategoriesByTaskId(taskId);
		return list;
	}
	@RequestMapping
	public @ResponseBody
	TaskProfile getTask4Bill(Long taskId) {

		TaskProfile taskProfile = taskService.getTask4Bill(taskId);
		return taskProfile;
	}
	@RequestMapping
	public @ResponseBody
	List<ComboBean>  goolgeTask(@RequestParam Map<String, Object> params) {
		return taskService.goolgeTask(params);
	}

	@RequestMapping
	public @ResponseBody
	List<ComboBean>  getAllTask() {
		return taskService.getAllTask();
	}
	@RequestMapping
	public @ResponseBody
	List<TkTask>  getAllTask2() {
		return taskService.getAllTask2();
	}
	
/*	@RequestMapping
	public @ResponseBody List<TaskLogVo> getLogListByTaskId(Long taskId){
		return taskService.getLogListByTaskId(taskId);
	}*/
	@RequestMapping
	public @ResponseBody
	PageBean getLogListByTaskId(PageParam pageParam,
			Long taskId) {

		PageBean pageBean = taskService.getLogListByTaskId(pageParam, taskId);
		return pageBean;
	}
 
	@RequestMapping
	public @ResponseBody
	TkTaskLog saveOrUpdateTaskLog(TkTaskLog tkTaskLog) {
		return taskService.saveOrUpdateTaskLog(tkTaskLog);
	}
	
	

	@RequestMapping
	public @ResponseBody
	TkTaskLog loadTaskLog(Long id) {
		return taskService.loadTaskLog(id);
	}

	@RequestMapping
	public @ResponseBody
	List<TkTaskStatus> getCurrentTaskStatusList(String code) {
		return taskService.getCurrentTaskStatusList(code);
	}
	
	
	@RequestMapping
	public @ResponseBody
	TkTaskStatus getCurrentStatusByTaskId(Long taskId) {
		return taskService.getCurrentStatusByTaskId(taskId);
	}
	
	
	
	@RequestMapping
	public @ResponseBody
	TkTask updateTaskStatus(Long taskId,String status) throws TmException {
		return taskService.updateTaskStatus(taskId,status);
	}
	
	@RequestMapping
	public @ResponseBody
	List<TkTaskStatus> getTaskStatusList() {
		return taskService.getTaskStatusList();
	}
	
	@RequestMapping 
	public void getImage(@RequestParam("id") Long id, 
	        HttpServletRequest request, HttpServletResponse response) { 
	    response.setHeader("Pragma", "No-cache"); 
	    response.setHeader("Cache-Control", "no-cache"); 
	    response.setDateHeader("Expires", 0);

	    TkImg  tkImg =this.taskService.getTkImg(id);

	    try { 
	        OutputStream outputStream = response.getOutputStream();
	        BufferedInputStream inputStream = new BufferedInputStream( 
	                new FileInputStream(tkImg.getPath())); 
	        byte[] data = new byte[1024]; 
	        for (int i = inputStream.read(data); i > 0; i = inputStream 
	                .read(data)) { 
	            outputStream.write(data, 0, i); 
	        } 
	        inputStream.close(); 
	    } catch (IOException e) { 
	        throw new RuntimeException(e); 
	    } 
	}
	
	@RequestMapping
    public void download(@RequestParam("id") Long id,HttpServletResponse response){  
        response.setCharacterEncoding("utf-8");  
        response.setContentType("multipart/form-data");  
        TkAttachment  tkAttachment =this.taskService.getTkAttachment(id);
        String path=tkAttachment.getPath();
        String fileName=path.substring(path.lastIndexOf("\\")+2, path.length());
        
        response.setHeader("Content-Disposition", "attachment;fileName=\""+fileName+"\"");  
        try {  
           // File file=new File(path);  
//            System.out.println(file.getAbsolutePath());  
            
            InputStream inputStream=new FileInputStream(path);  
            OutputStream os=response.getOutputStream();  
            byte[] b=new byte[1024];  
            int length;  
            while((length=inputStream.read(b))>0){  
                os.write(b,0,length);  
            }  
            inputStream.close();  
        } catch (FileNotFoundException e) {  
            e.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
    } 
	
	@RequestMapping
	public  @ResponseBody List<TkImg> getImageListByTaskId(Long taskId){
		
		return taskService.getImageListByTaskId(taskId);

	}
	@RequestMapping
	public  @ResponseBody List<TkAttachment> getAttachmentListByTaskId(Long taskId){
		
		return taskService.getAttachmentListByTaskId(taskId);

	}
 
	@RequestMapping
	public @ResponseBody
	Long[] deleteTkImg(Long[] ids) {
		taskService.deleteTkImg(Arrays.asList(ids));
		 return ids;
	}
	
	@RequestMapping
	public @ResponseBody
	Long[] deleteTkAttachment(Long[] ids) {
		taskService.deleteTkAttachment(Arrays.asList(ids));
		 return ids;
	}
	
	
}
